import json
import requests
from module.common import Common

class Github:
    "github.com 操作类"

    # 用户ID
    uid = None
    # 一个会话
    session = None

    # 初始化
    def __init__(self):
        self.session = requests.Session()

    # 注册
    def reg(self, user, pwd, email):

        code      = self.session.get("https://github.com/join?source=header-home").text

        token     = Common.getMiddle(code, '<input name="authenticity_token" type="hidden" value="', '" />')
        timestamp = Common.getMiddle(code, '<input class="form-control" name="timestamp" type="hidden" value="', '" />')
        secret    = Common.getMiddle(code, '<input class="form-control" name="timestamp_secret" type="hidden" value="', '" />')

        req = self.session.post("https://github.com/join", data={
            "utf8": "✓",
            "authenticity_token": token,
            "user[login]": user,
            "user[email]": email,
            "user[password]": pwd,
            "source": "header-home",
            "timestamp": timestamp,
            "timestamp_secret": secret
        })
        return req.text.find("Welcome to GitHub") != -1

    # 登录
    def login(self, email, pwd):

        code  = self.session.get("https://github.com/login").text
        token = Common.getMiddle(code, '<input name="authenticity_token" type="hidden" value="', '" />')

        req = self.session.post("https://github.com/session", data={
            "commit": "Sign in",
            "utf8": "✓",
            "authenticity_token": token,
            "login": email,
            "password": pwd
        })

        self.uid = Common.getMiddle(req.text, 'name="octolytics-dimension-region_render" /><meta content="', '"')

        return req.text.find("Learn Git and") != -1

    # 上传头像
    def upload(self):

        # 获取上传权限
        token = Common.getMiddle(
            self.session.get("https://github.com/settings/profile").text,
            'data-upload-policy-authenticity-token="', '"'
        );
        req = self.session.post("https://github.com/upload/policies/avatars", data={
            "name": "yazi1.jpg",
            "size": "22583",
            "content_type": "image/jpeg",
            "authenticity_token": token,
            "owner_type": "User",
            "owner_id": self.uid
        })
        obj   = json.loads(req.text)
        token = obj["upload_authenticity_token"]
        auth  = obj["header"]["GitHub-Remote-Auth"]

        # 上传图片到 Github 的头像服务器
        req = self.session.post(
            "https://uploads.github.com/storage/avatars",
            data={
                "authenticity_token": token,
                "owner_type": "User",
                "owner_id": self.uid,
                "size": "22583",
                "content_type": "image/jpeg"
            },
            files={'file': open('../yazi.jpg', 'rb')},
            headers={"GitHub-Remote-Auth": auth}
        )

        # 获取保存头像时用到的token
        tid = str(json.loads(req.text)["id"])
        req = self.session.get("https://github.com/settings/avatars/" + tid)
        token = Common.getMiddle(req.text, '<input name="authenticity_token" type="hidden" value="', '" />')

        # 保存头像
        req = self.session.post("https://github.com/settings/avatars/" + tid, data={
            "utf8": "✓",
            "authenticity_token": token,
            "cropped_x": "0",
            "cropped_y": "0",
            "cropped_width": "0",
            "cropped_height": "0",
            "op": "save"
        })

        return req.text.find("Your profile picture has been updated.") != -1

    # 激活账号
    def active(self, url):
        return self.session.get(url).text.find("Your email was verified") != -1

